<?php
namespace Manage\Model;
use Think\Model;
class DownloadModel extends Model{
	private $Model;
	function _initialize(){
		$this->Model=M('DownloadDescription');
	}
	public function operDownload($data,$download_id=0){
		$download_data=$this->create($data);
		if($download_id){
			$map['download_id']=$download_id;
			$this->where($map)->save($download_data);
		}else{
			$download_data['date_added']=time();
			$download_id=$this->add($download_data);
		}
		$map=array('download_id'=>$download_id);
		$this->Model->where($map)->delete();
		foreach($data['download_description'] as $language_id => $download_description){
			$download_description['language_id']=$language_id;
			$download_description['download_id']=$download_id;
			$this->Model->add($download_description);
		}
	}
	public function getDownload($download_id=0){
		$map['download_id']=$download_id;
		$download=$this->where($map)->find();
		if($download){
			$download_description=$this->Model->where($map)->select();
			foreach ($download_description as $v) {
				$download_description[$v['language_id']]=$v;
			}
			$download['download_description']=$download_description;
		}
		return $download;
	}

	public function getDownloads($data){
		$page=array(
			'start'		=>	$data['start']?$data['start']:0,
			'limit'		=>	$data['limit']?$data['limit']:20
			);
		$map=array(
			'language_id'	=>	get_default_lng_id()
			);
		if(isset($data['name'])) $map['name']=array('like',"%".$data['name']."%");
		$downloads=$this->join("LEFT JOIN __DOWNLOAD_DESCRIPTION__ ON __DOWNLOAD__.download_id = __DOWNLOAD_DESCRIPTION__.download_id")->where($map)->field(C('DB_PREFIX').'download.download_id,filename,mask,date_added,name')->limit($page['start'],$page['limit'])->select();
		return $downloads;
	}

	public function getDownloadTotal($data){
		$map=array(
			'language_id'	=>	get_default_lng_id()
			);
		if(isset($data['name'])) $map['name']=array('like',"%".$data['name']."%");
		$total=$this->join("LEFT JOIN __DOWNLOAD_DESCRIPTION__ ON __DOWNLOAD__.download_id = __DOWNLOAD_DESCRIPTION__.download_id")->where($map)->field(C('DB_PREFIX').'download.download_id,filename,mash,date_added,name')->count();
		return $total;
	}

	public function del($download_id){
		$map['download_id']	= (int) $download_id;
		$download=$this->where($map)->find();
		$count=0;
		if(isset($download['filename'])){
			$file=C('DOWNLOAD_DIR') . $download['filename'];
			if(is_file($file)) unlink($file);
			$this->Model->where($map)->delete();
			$count=$this->where($map)->delete();
			D('ProductToDownload')->where($map)->delete();
			D('ArticleToDownload')->where($map)->delete();
		}
		return $count;
	}
}